<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue</title>
</head>
<body>
<div id="app">
    <h1>{{ count }}</h1>
    <button @click="increment">+10</button>
</div>

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.5.1/dist/vuex.js"></script>
<script>
    // 声明状态管理机
    const store = new Vuex.Store({
        state: {
            count: 0 // 也可以是对象
        },
        mutations: {
            // mutations里的修改方法必须是同步的，不可以异步实现
            increment(state, n) {
                state.count += n;
            },
            // 对象传参
            increment2(state, payload) {
                state.count += payload.n;
            },
        }
    });

    let vm = new Vue({
        el: "#app",
        data: {
            count: 0,
        },
        methods: {
            increment() {
                // commit并传参
                this.$store.commit('increment', 10);
                // 等同于
                // this.$store.commit({
                //     type: 'increment',
                //     n: 10
                // });
                // 对象传参
                this.$store.commit('increment2', {
                    n: 10
                });

                // console.log(this.$store.state.count);
                this.count = this.$store.state.count;
            }
        },
        // 注入状态管理器
        store: store
    });
</script>
</body>
</html>
